import importlib

# Create your views here.
from django.views import View
from rest_framework.views import APIView

from DjangoPark import settings
from utils.utils.ResultResponse import dataResponse


class SwaggerView(View):
    """swagger文档"""

    @staticmethod
    def convert_model(cls):
        """
        判定类型
        :param cls: 类
        :return:
        """
        return {
            item.name: {
                "name": item.verbose_name,
                "type": item.__class__.__name__
            }
            for item in cls._meta.fields
        }

    @staticmethod
    def convert_form(cls):
        """
        判定类型
        :param cls: 类
        :return:
        """
        return {
            item: {
                "name": dict(cls.declared_fields)[item].label,
                "type": dict(cls.declared_fields)[item].__class__.__name__
            }
            for item in dict(cls.declared_fields)
        }

    @staticmethod
    def convert_serializer(cls):
        """
                判定类型
                :param cls: 类
                :return:
                """
        return {
            item: {
                "name": dict(cls.declared_fields)[item].label,
                "type": dict(cls.declared_fields)[item].__class__.__name__
            }
            for item in dict(cls.declared_fields)
        }

    def get(self, request):
        """swagger文档获取"""
        module = importlib.import_module(settings.ROOT_URLCONF)
        swagger_list = []
        if hasattr(module, 'urlpatterns'):
            url_list = getattr(module, 'urlpatterns')
            for item in url_list:
                url_pattern_list = item.__dict__['url_patterns']
                for url_pattern in url_pattern_list:
                    if 'view_class' in url_pattern.__dict__:
                        view_class = url_pattern.__dict__['view_class']
                        print('---------------------')
                        swagger_dict = {}
                        swagger_dict['swagger_title'] = view_class.api_tags or view_class.__name__
                        swagger_dict['url_path'] = "http://%s/%s" % (request.get_host(), view_class.url_path)
                        swagger_dict['model_class'] = SwaggerView.convert_model(view_class.model_class)
                        swagger_dict['request_verify_class'] = SwaggerView.convert_form(view_class.request_verify_class)
                        # swagger_dict['response_serializer_class'] = SwaggerView.convert_serializer(
                        #     view_class.response_serializer_class)
                        swagger_list.append(swagger_dict)
                        print('---------------------')
        print(swagger_list)
        return dataResponse(data=swagger_list)
